package com.itheima.leadnews.admin.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.dto.AdUserDto;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.itheima.leadnews.admin.mapper.AdUserMapper;
import com.itheima.leadnews.admin.service.AdUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //根据name查询数据库
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(queryWrapper);
        //判断用户是否存在
        if (adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在,判断密码是否正确,前端传来的密码 + 数据库里的盐MD5加密
        String passWord = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if (!passWord.equals(adUser.getPassword())){
            //不相等,密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //相等,登录成功,将登录信息响应给前端,排除密码和盐,生成token
        adUser.setPassword("");
        adUser.setSalt("");
        Map<String,Object> map = new HashMap<>();
        map.put("user",adUser);
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        return ResponseResult.okResult(map);
    }
}
